#include "skyex.h"
#include "rtklib.h"
#include "Rnxeph.h"
#include "StreamObs.h"
#include "BaseStation.h"

skyex_t* newskyex()
{
    skyex_t* obj = malloc(sizeof(skyex_t));
    memset(obj, 0, sizeof(skyex_t));      
    init_rtcm(&obj->m_rtcm);
    memset(obj->m_rtcm.nav.glo_fcn,0,sizeof(obj->m_rtcm.nav.glo_fcn)); // It's better to add this into init_rtcm, or it will cause some INVALID WRITE. jyh  
    return  obj;
}

void freenewskyex(skyex_t* obj){
    free_rtcm(&obj->m_rtcm);
    free(obj);
}


void skyex_inputbuf(skyex_t* obj, char *buff, int nbyte){
    int ret = 0;
    double ep[6], sow;
    int week;

    //printf("buff:%s nbyte:%d\n",buff,nbyte);
    for (int i = 0; i < nbyte; i++) {
        ret = input_rtcm3(&obj->m_rtcm, buff[i]);
        if(ret == 5){
            // antenna
             printf("*****WARNING(StreamObs.c): Not support antenna!\n");
        }
        if(ret == 1){
            // observation
            printf("*****WARNING(StreamObs.c): Not support observation!\n");
        }
        if(ret == 2){
            //StreamObs_m_setEphData(&obj->m_rtcm.nav,obj->m_rtcm.ephsat);
            // if (mjd==0&&sod==0){
            // memset(ep,0,sizeof(ep));
            // time2epoch(obj->m_rtcm.time,ep);
            // sow = time2gpst(obj->m_rtcm.time,&week);
            // wksow2mjd(week,sow,&DLY.mjd,&DLY.sod);
            // }else{
            //     DLY.mjd=mjd;
            //     DLY.sod=sod;
            // }
            //printf("ret:2\n");
            StreamObs_m_setEphData(&obj->m_rtcm.nav,obj->m_rtcm.ephsat);
        }
        if(ret>0){
            //printf("ret:0\n");
            free_rtcm(&obj->m_rtcm);
            init_rtcm(&obj->m_rtcm);
            //freenewskyex(obj);
            //newskyex();
        }
    }
    return ret;
}
void m_readJsonFile_t() {
    int isys, curmjd, i, isit, j, satsize, sitsize;
    cJSON* root;
    //int iargc, iy, im, id, ih, imi;
    double cursod, dsec;
    char *curItem, *line;
    //vector<string> strtmp;
    char value[1024]={0}, cex, key[256], fmt[512], mode[256], checkv[256], _jsonFile[256], buf[128] = { 0 };
    line=calloc(LEN_STRING+1,sizeof(char));
    curItem=calloc(256+1,sizeof(char));
    DLY.SAT=calloc(MAXSAT, sizeof(struct Satellite));
    DLY.SIT=calloc(MAXSIT, sizeof(struct Station));
    for(i=0;i<MAXSAT;i++) DLY.cprn[i]=calloc(LEN_PRN,sizeof(char));
    memset(&DLY.mTable, 0, sizeof(struct mTable));
    DLY.m_unsyncConn=(stream_t*)calloc(1,sizeof(stream_t));
    strinit(DLY.m_unsyncConn);

    //////////////// change work direction ///////////////
    // char *cwd=calloc(LEN_STRING,sizeof(char));
    // char *tmpcwd=getcwd(NULL, NULL), *tmpfree=tmpcwd;
    // int lentmp;
    // strcpy(cwd,tmpcwd);
    // tmpcwd=strtok(tmpcwd, "/");
    // while( tmpcwd != NULL ) {
    //     lentmp=strlen(tmpcwd);
    //     tmpcwd = strtok(NULL, "/");
    //     if(tmpcwd==NULL){
    //         memcpy(cwd+strlen(cwd)-lentmp,"\0",sizeof(char)*lentmp);
    //     }
    // }
    // chdir(cwd);
    // free(tmpfree);
    // free(cwd);

    //////////////// parse command line ///////////////
    // for (i = 1; i < argc; i++) {
    //     if (strstr(args[i], "-mode")) {
    //         strcpy(mode, args[++i]);
    //         strcpy(_jsonFile, args[++i]);
    //     }
    //     if (strstr(args[i], "-post"))
    //         DLY.lpost = true;
    //     if (strstr(args[i], "-pthread"))
    //         DLY.lmthread = true;
    //     if (strstr(args[i], "-debug"))
    //         DLY.ldebug = true;
    // }

    // parse the configure here
    // char* json_str =json_loader("vrs.json");
    // root=cJSON_Parse(json_str);
    // if (!root) {
    //     printf("Error before: [%s]\n",cJSON_GetErrorPtr());
    // }

    /////////////////////////////// tables directory part //////////////////
    //strcpy(curItem,"path");
    // excludeAnnoValue(DLY.ephdir, cJSON_GetChildValue(root,curItem,"broad"));
    // excludeAnnoValue(DLY.precisedir, cJSON_GetChildValue(root,curItem,"precise"));
    // excludeAnnoValue(DLY.tracedir, cJSON_GetChildValue(root,curItem,"trace"));
    // excludeAnnoValue(DLY.obsdir, cJSON_GetChildValue(root,curItem,"obs"));
    // excludeAnnoValue(DLY.qcdir, cJSON_GetChildValue(root,curItem,"qclog"));
    // excludeAnnoValue(DLY.outdir, cJSON_GetChildValue(root,curItem,"output"));

    // excludeAnnoValue(DLY.ephdir, "./brdm/brdm-DDD-0.-YY-p");
    // excludeAnnoValue(DLY.precisedir, "igs");
    // excludeAnnoValue(DLY.tracedir, cJSON_GetChildValue(root,curItem,"trace"));
    // excludeAnnoValue(DLY.obsdir, cJSON_GetChildValue(root,curItem,"obs"));
    // excludeAnnoValue(DLY.qcdir, cJSON_GetChildValue(root,curItem,"qclog"));
    // excludeAnnoValue(DLY.outdir, cJSON_GetChildValue(root,curItem,"output"));
    //memset(curItem, 0, sizeof(char)*strlen(curItem));

    strcpy(DLY.ephdir, "./brdm/brdm-DDD-0.-YY-p");
    strcpy(DLY.precisedir, "igs");
    strcpy(DLY.tracedir, "trace0");
    strcpy(DLY.obsdir, "./obs/-YYYY-/-DDD-/");
    strcpy(DLY.qcdir, "qc");
    strcpy(DLY.outdir, "./obs_gen/");

    //strcpy(curItem,"files");
    //excludeAnnoValue(DLY.tablesConfig, cJSON_GetObjectItem(root,curItem)->valuestring);
    //strcpy(DLY.tablesConfig, "./tables.json");
    //m_parseTablesConfigures(DLY.tablesConfig);

    // strcpy(DLY.mTable.object, value);
    // strcpy(DLY.mTable.stacoo, value);
    // strcpy(DLY.mTable.satnav, value);
    // strcpy(DLY.mTable.antnam, value);
    // strcpy(DLY.mTable.antpcv, value);
    // strcpy(DLY.mTable.gptgrd, value);
    // strcpy(DLY.mTable.leapsc, value);
    // strcpy(DLY.mTable.ocload, value);
    // strcpy(DLY.mTable.jpleph, value);
    // strcpy(DLY.mTable.ut1t96, value);
    // strcpy(DLY.mTable.ut1t03, value);
    // strcpy(DLY.mTable.ut1t10, value);
    // strcpy(DLY.mTable.pndfln, value);
    // strcpy(DLY.mTable.polut1, value);
    // strcpy(DLY.mTable.corrp1c1, value);
    // strcpy(DLY.mTable.database, value);
    // strcpy(DLY.mTable.corrDCB, value);
    // strcpy(DLY.mTable.gptgrd_w, value);
    // strcpy(DLY.mTable.subnet, value);
    // strcpy(DLY.mTable.baselines, value);
    // strcpy(DLY.mTable.rtconfigs, value);
    // strcpy(DLY.mTable.corrStaDCB, value);

   // sscanf(value, "%d%d%d%d%d%lf%lf", &iy, &im, &id, &ih, &imin, &dsec, &DLY.seslen);
    int iy,im,id,ih,imin;
    iy=2021,im=4,id=1,ih=0,imin=0,dsec=30;
    DLY.seslen=7200;
    yr2year(&iy);
    DLY.mjd0 = md_julday(iy, im, id);
    DLY.sod0 = ih * 3600 + imin * 60 + dsec;
    DLY.mjd1 = (int) (DLY.mjd0 + (DLY.sod0 + DLY.seslen) / 86400);
    DLY.sod1 = DLY.sod0 + DLY.seslen - (DLY.mjd1 - DLY.mjd0) * 86400.0;
    DLY.dintv=1;

    strcpy(DLY.freq_obs[0][0],"L1");
    strcpy(DLY.freq_obs[0][1],"L2");
    strcpy(DLY.freq_obs[0][2],"L5");

    strcpy(DLY.freq_obs[1][0],"L1");
    strcpy(DLY.freq_obs[1][1],"L2");

    strcpy(DLY.freq_obs[2][0],"L1");
    strcpy(DLY.freq_obs[2][1],"L5");
    strcpy(DLY.freq_obs[2][2],"L7");

    strcpy(DLY.freq_obs[3][0],"L2");
    strcpy(DLY.freq_obs[3][1],"L5");
    strcpy(DLY.freq_obs[3][2],"L7");
    strcpy(DLY.freq_obs[3][3],"L6");

    strcpy(DLY.freq_obs[6][0],"L1");
    strcpy(DLY.freq_obs[6][1],"L2");
    strcpy(DLY.freq_obs[6][2],"L5");

    DLY.nfreq_obs[0]=3;
    DLY.nfreq_obs[1]=2;
    DLY.nfreq_obs[2]=3;
    DLY.nfreq_obs[3]=4;
    DLY.nfreq_obs[4]=0;
    DLY.nfreq_obs[5]=0;
    DLY.nfreq_obs[6]=3;
    DLY.nfreq_obs[7]=0;

    memcpy(DLY.freq,DLY.freq_obs,sizeof(DLY.freq));
    memcpy(DLY.nfreq,DLY.nfreq_obs,sizeof(DLY.nfreq));

    DLY.maxthd=4;
    DLY.tracelevel=1;

    strcpy(DLY.sitname,"TEMP");
    // DLY.m_reqs[0].msgid=-1;
    // DLY.m_reqs[0].staid=-1;
    // DLY.m_reqs[0].x[0]=0;
    // DLY.m_reqs[0].x[1]=0;
    // DLY.m_reqs[0].x[2]=0;
   
    strcpy(DLY.ptr_atomConnector,"127.0.0.1:5001");
    strcpy(DLY.ptr_outProtocol,"");
    strcpy(DLY.ptr_vrsConnector,"");
    strcpy(DLY.ptr_inProtocol,"NTRIP");
    strcpy(DLY.ptr_obsConnector,"kplvrs:1234@119.96.242.26:15005/HB02");
    strcpy(DLY.ptr_ephConnector,"TCPSYNC@RTCM3=119.96.169.117:7001");
    
    for(i=0;i<139;i++){
        if (i<=31){
            sprintf(DLY.cprn[i],"G%02d",i+1);
        }else if(i>=32&&i<=55){
            sprintf(DLY.cprn[i],"R%02d",i-31);
        }else if(i>=56&&i<=57){
            sprintf(DLY.cprn[i],"R%02d",i-30);
        }else if(i>=58&&i<=71){
            sprintf(DLY.cprn[i],"C%02d",i-57);
        }else if(i==72){
            sprintf(DLY.cprn[i],"C%02d",16);
        }else if(i>=73&&i<=103){
            sprintf(DLY.cprn[i],"C%02d",i-55);
        }else if(i>=104&&i<=108){
            sprintf(DLY.cprn[i],"C%02d",i-48);
        }else if(i>=109&&i<=113){
            sprintf(DLY.cprn[i],"E%02d",i-108);
        }else if(i>=114&&i<=116){
            sprintf(DLY.cprn[i],"E%02d",i-107);
        }else if(i>=117&&i<=121){
            sprintf(DLY.cprn[i],"E%02d",i-106);
        }else if(i>=122&&i<=126){
            sprintf(DLY.cprn[i],"E%02d",i-104);
        }else if(i>=127&&i<=130){
            sprintf(DLY.cprn[i],"E%02d",i-103);
        }else if(i>=131&&i<=132){
            sprintf(DLY.cprn[i],"E%02d",i-101);
        }else if(i==133){
            sprintf(DLY.cprn[i],"E%02d",33);
        }else if(i==134){
            sprintf(DLY.cprn[i],"E%02d",36);
        }else if(i>=135&&i<=137){
            sprintf(DLY.cprn[i],"J%02d",i-134);
        }else{
            sprintf(DLY.cprn[i],"J%02d",7);
        }
    }
    strcpy(DLY.system,"GRCEJ");
    DLY.nsys=5;
    //memset(curItem, 0, sizeof(char)*strlen(curItem));

    //strcpy(curItem,"common");
    //m_readJsonItem(root, curItem);
    //memset(curItem, 0, sizeof(char)*strlen(curItem));

    // strcpy(curItem,"reqs");
    // m_readJsonItem(root, curItem);
    // memset(curItem, 0, sizeof(char)*strlen(curItem));

    // strcpy(curItem,"vrs");
    // m_readJsonItem(root, curItem);
    // memset(curItem, 0, sizeof(char)*strlen(curItem));

    // Satllite Part
//     strcpy(curItem,"SAT");
//     FILE *f;
//     if ((f=fopen("session.obj_out", "r"))==NULL){
//         printf("file = %s,can't open file to read", DLY.mTable.object);
//         exit(1);
//     }

//     DLY.nprn = DLY.nsys = 0;
//     memset(DLY.system, 0, sizeof(DLY.system));
//     strcpy(fmt, "%s%s%s%s%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf");
//     satsize=0;
//     while (fgets(line, LEN_STRING, f))
//     {
//         if (strstr(line, "-Satellite used")) break;
//         if (line[0] != ' ') continue;
//         struct Satellite itemSat;
//         Satellite_initial(&itemSat);
//         sscanf(line, fmt, itemSat.cprn, itemSat.type, itemSat.pcv,\
//                itemSat.clk, &itemSat.dclk0, &itemSat.qclk, itemSat.dx0,\
//                itemSat.dx0 + 1, itemSat.dx0 + 2, itemSat.dx0 + 3,\
//                itemSat.dx0 + 4, itemSat.dx0 + 5, itemSat.dx0 + 6,\
//                itemSat.dx0 + 7, itemSat.dx0 + 8, itemSat.dx0 + 9,\
//                itemSat.dx0 + 10, itemSat.dx0 + 11, itemSat.dx0 + 12,\
//                itemSat.dx0 + 13, itemSat.dx0 + 14, itemSat.dx0 + 15,\
//                itemSat.dx0 + 16, itemSat.dx0 + 17, itemSat.dx0 + 18,\
//                itemSat.dx0 + 19, itemSat.dx0 + 20);
//         for (i = 0; i < 6; i++)
//             itemSat.dx0[i] = itemSat.dx0[i] * 1E-3;
//         if (-1 != pointer_string(satsize, DLY.cprn, (char*)(itemSat.cprn))){
//             printf("cprn = %s,exist the same satellite", itemSat.cprn);
//             continue;
//         }
//         strcpy(DLY.cprn[satsize],itemSat.cprn);
//         if (-1 == (index_string(DLY.system, itemSat.cprn[0])))
//         {
//             DLY.system[DLY.nsys] = itemSat.cprn[0];
//             DLY.nsys = DLY.nsys + 1;
//         }
//         isys = index_string(SYS, itemSat.cprn[0]);
//         if (isys == -1)
//         {
//             printf("system = %c,do not support system", itemSat.cprn[0]);
//             exit(1);
//         }

//         if (DLY.lpost) // post
//         {
//             if (0 == Antatx_s_rdSvnav(
//                     itemSat.cprn, DLY.mjd0 + DLY.sod0 / 86400.0,
//                     itemSat.type, &itemSat.mass, &itemSat.ifreq,
//                     itemSat.offs, itemSat.sid, itemSat.svn))
//                 exit(1);

//             get_freq(&itemSat, "RAW", DLY.nfreq_obs[isys], DLY.freq_obs[isys]);
//             get_freq(&itemSat, "RAW", DLY.nfreq[isys], DLY.freq[isys]);

//             // copy back to the frequency_obs,frequency_obs is the same with the first nfreq[isys]
// /*
//             for (isys = 0; isys < MAXSYS; isys++)
//             {
//                 for (i = 0; i < DLY.nfreq[isys]; i++)
//                 {
//                     if (-1 == (j = pointer_charstr(MAXFREQ, LEN_FREQ, (char*)DLY.freq_obs[isys], DLY.freq[isys][i])))
//                     {
//                         printf( "freq = %s,this frequency is not contained in " "the freq_obs", DLY.freq[isys][i]);
//                         exit(1);
//                     }
//                     char* s = DLY.freq_obs[isys][i];
//                     memcpy(DLY.freq_obs[isys][i], DLY.freq_obs[isys][j],
//                            sizeof(char) * LEN_FREQ);
//                     memcpy(DLY.freq_obs[isys][j], s, sizeof(s));
//                 }
//             }
// */

//             Antatx_m_resetMem(&itemSat.AX);

//             if (0 == Antatx_m_getAnt(&itemSat.AX,
//                     itemSat.cprn, DLY.nfreq_obs, DLY.freq_obs,
//                     DLY.mjd0 + DLY.sod0 / 86400.0,
//                     DLY.mjd1 + DLY.sod1 / 86400.0, itemSat.type,
//                     itemSat.cprn, itemSat.xyz, NULL))
//             {
//                 printf( "ant = %s,cprn = %s,satellite antenna is not found in " "atx file", itemSat.type, itemSat.cprn);
//                 exit(1);
//             }
//         }
//         itemSat.isabled = true;
//         DLY.SAT[satsize]=itemSat;
//         satsize++;
//     }
    satsize=139;
    DLY.nprn=139;
    // if (0 == (DLY.nprn = satsize))
    // {
    //     printf("nrpn = %d,no selected satellite!", DLY.nprn);
    //     //exit(1);
    // }
    /////////////////////////////////////////////////////////////////////
    for (i=0; i<satsize; i++)
    {
        updateSatfreq(&DLY.SAT[i]);
    }
    i = index_string(DLY.system, 'G');
    if (-1 == i)
    {
        i = index_string(DLY.system, 'R');
        if (-1 == i)
            i = index_string(DLY.system, 'E');
    }
    if (i > 0)
    {
        cex = DLY.system[i];
        DLY.system[i] = DLY.system[0];
        DLY.system[0] = cex;
    }
    DLY.iref = index_string(SYS, DLY.system[0]);
    if (strstr(DLY.cobs, "RAW"))
    {
        for (i = 0; i < MAXSYS; i++)
            DLY.nfq[i] = DLY.nfreq[i];
    }
    else
    {
        for (i = 0; i < MAXSYS; i++)
            DLY.nfq[i] = 1;
    }
    DLY.nsit=1;
    DLY.maxthd=4;
    DLY.tracelevel=1;
    DLY.seslen=7200;
    DLY.lastAct=1653355076;
    for (i=0;i<8;i++){
        DLY.nfq[i]=0;
    }
    //memset(curItem, 0, sizeof(char)*strlen(curItem));

    ////////////////////////////Stations Part //////////////////////////
    // strcpy(curItem,"SIT");
    // while (fgets(line, LEN_STRING, f))
    // {
    //     if (strstr(line, "+Station used"))
    //         break;
    // }
    // if (feof(f))
    // {
    //     printf("no records for stations");
    //     exit(1);
    // }
    // DLY.nsit = 0;
    // strcpy(fmt,
    //        "%s%s%s%s%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%s%lf%lf%lf%"
    //        "lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf%lf");
    // sitsize=0;
    // while (fgets(line, LEN_STRING, f)) {
    //     if (strstr(line, "-Station used"))
    //         break;
    //     if (line[0] != ' ')
    //         continue;
    //     struct Station itemSit;
    //     Station_initial(&itemSit);
    //     itemSit.staID = sitsize + 1;
    //     sscanf(line, fmt, itemSit.name, itemSit.skd, itemSit.pcv, itemSit.clk,
    //            itemSit.dclk0, itemSit.qclk, itemSit.dclk0 + 1,
    //            itemSit.qclk + 1, itemSit.dclk0 + 2, itemSit.qclk + 2,
    //            itemSit.dclk0 + 3, itemSit.qclk + 3, itemSit.dclk0 + 4,
    //            itemSit.qclk + 4, itemSit.dclk0 + 5, itemSit.qclk + 5,
    //            itemSit.dclk0 + 6, itemSit.qclk + 6, &itemSit.cutoff,
    //            itemSit.map, &itemSit.dztd0, &itemSit.qztd, &itemSit.dgrd0,
    //            &itemSit.qgrd, &itemSit.dion0, &itemSit.qion, itemSit.sigr,
    //            itemSit.sigp, itemSit.sigr + 1, itemSit.sigp + 1,
    //            itemSit.sigr + 2, itemSit.sigp + 2, itemSit.sigr + 3,
    //            itemSit.sigp + 3, itemSit.sigr + 4, itemSit.sigp + 4,
    //            itemSit.sigr + 5, itemSit.sigp + 5, itemSit.sigr + 6,
    //            itemSit.sigp + 6);
    //     itemSit.cutoff = itemSit.cutoff * DEG2RAD;
    //     //////////////////// Reading Station Coordinates here/////////////
    //     if (!read_siteinfo(&itemSit)) {
    //         printf("station = %s,read coordinate error!", itemSit.name);
    //         exit(1);
    //     }
    //     strcpy(DLY.sitname[sitsize], itemSit.name);
    //     if (DLY.lpost)
    //     {
    //         Patterns_readFile();
    //         mjd2date(DLY.mjd0, DLY.sod0, &iy, &im, &id, &ih, &imi, &dsec);
    //         sprintf(itemSit.obsfile, "%s%c", DLY.obsdir, FILEPATHSEP);
    //         Patterns_m_getPatternName(true, "", "", iy, im, id, ih, itemSit.obsfile);
    //         sprintf(key, "STANAM=%s", toLower(DLY.sitname[sitsize]));
    //         toUpper(DLY.sitname[sitsize]);
    //         Patterns_m_getPatternName(false, "rnxo", key, iy, im, id, ih, itemSit.obsfile + strlen(itemSit.obsfile));
    //         sprintf(itemSit.logFile, "%s%c", DLY.qcdir, FILEPATHSEP);
    //         Patterns_m_getPatternName( false, "log", key, iy, im, id, ih, itemSit.logFile + strlen(itemSit.logFile));
    //         if (access(itemSit.obsfile, 0) != 0)
    //         {
    //             printf("file = %s,can't find obs file", itemSit.obsfile);
    //         }
    //         if (itemSit.x[0] * itemSit.x[1] * itemSit.x[2] != 0)
    //         {
    //             xyzblh(itemSit.x, 1.0, 0, 0, 0, 0, 0, itemSit.geod);
    //             rot_enu2xyz(itemSit.geod[0], itemSit.geod[1],
    //                         itemSit.rot_l2f);
    //             memcpy(itemSit.refx, itemSit.x, sizeof(double) * 3);
    //             // oceanload_coef(itemSit.geod[0],itemSit.geod[1],itemSit.olc);
    //         }
    //         else
    //         {
    //             if (itemSit.skd[0] == 'F')
    //             {
    //                 printf( "station = %s,fix mode for no coordinate station,will continue", itemSit.name);
    //                 continue;
    //             }
    //         }
    //         if (0 == Antatx_s_antnam(itemSit.name, itemSit.anttyp, key)) exit(1);
    //         if (0 == Antatx_m_getAnt(&itemSit.AX, "SITE", DLY.nfreq, DLY.freq, DLY.mjd0 + DLY.sod0 / 86400.0, DLY.mjd1 + DLY.sod1 / 86400.0, trim(key), "", NULL, itemSit.enu))
    //         {
    //             printf( "ant = %s,sitename = %s,station antenna is not found " "in atx file", trim(key), itemSit.name);
    //             exit(1);
    //         }
    //     }
        /*else
        {
            cur_time(&curmjd, &cursod);
            if (itemSit.x[0] * itemSit.x[1] * itemSit.x[2] != 0)
            {
                xyzblh(itemSit.x, 1.0, 0, 0, 0, 0, 0, itemSit.geod);
                rot_enu2xyz(itemSit.geod[0], itemSit.geod[1],
                            itemSit.rot_l2f);
                // oceanload_coef(itemSit.geod[0], itemSit.geod[1],
                // itemSit.olc);
                memcpy(itemSit.refx, itemSit.x, sizeof(double) * 3);
            }
            else
            {
                if (itemSit.skd[0] == 'F')
                {
                    LOGPRINT(
                            "station = %s,fix mode for no coordinate station",
                            itemSit.name.c_str());
                    LOGE("station = %s,fix mode for no coordinate station",
                         itemSit.name.c_str());
                    continue;
                }
            }
            if (0 == Antatx::s_antnam(itemSit.name.c_str(),
                                      itemSit.anttyp.c_str(), key))
                exit(1);
            if (0 == itemSit.AX.m_getAnt("SITE", this->nfreq, this->freq,
                                         curmjd + cursod / 86400.0,
                                         curmjd + cursod / 86400.0,
                                         trim(key), "", NULL,
                                         itemSit.enu))
            {
                LOGE(
                        "ant = %s,sitename = %s,station antenna is not found "
                        "in atx file",
                        trim(key), itemSit.name.c_str());
                LOGPRINT(
                        "ant = %s,sitename = %s,station antenna is not found "
                        "in atx file",
                        trim(key), itemSit.name.c_str());
                exit(1);
            }
        }*/
    //     DLY.SIT[sitsize]=itemSit;
    //     DLY.nsit = DLY.nsit + 1;
    //     sitsize++;
    //     free(itemSit.anttyp);
    //     free(itemSit.rectyp);
    // }
    // fclose(f);
    // if (DLY.nsit == 0 && DLY.promode != PRO_RTORB)
    // {
    //     printf("nsit = %d,no stations is selected", DLY.nsit);
    //     exit(1);
    // }
    // if (DLY.promode == PRO_RTK || DLY.promode == PRO_NRTK || (DLY.lpost && DLY.promode == PRO_VRS))
    //     Deploy_m_readBaselines();
/*

    Logtrace::s_defaultlogger.m_openLog("Stablh");
    for (isit = 0; isit < this->SIT.size(); isit++)
    {
        Logtrace::s_defaultlogger.m_wtMsg(
                "@%s %s %15.9lf %15.9lf %7.4lf\n", "Stablh",
                SIT[isit].name.c_str(), SIT[isit].geod[0] * RAD2DEG,
                SIT[isit].geod[1] * RAD2DEG, SIT[isit].geod[2]);
    }
    Logtrace::s_defaultlogger.m_closeLog("Stablh");
*/
    // struct stat st;
    // stat(DLY.tablesConfig, &st);
    // DLY.lastAct = st.st_mtime;
    //////////////////////////////////////////////////////////////////////////////
    // Deploy_m_checkConfigure();
    ////////////// check real-time configures
    ///////////////////////////////////////
    // if (!DLY.lpost)
    //     Deploy_m_checkRtConfigures();

    // memset(curItem, 0, sizeof(char)*strlen(curItem));
    // free(json_str);
    // free(line);
    // free(curItem);
    // cJSON_Delete(root);
}

int skyex_calcu(skyex_t* obj, double stax[3], char *outBuf,int mjd2,double sod2){
    double xsat_f[6], r1[6], r1leng, deltaDwe, tdelay;
    double geod[3], sod,sod_send, dump[3], ddelay;
    double rot_l2f[3][3], delay;
    int mjd,isat, jd_send, j, lorb;
    mjd=DLY.mjd=mjd2;
    sod=DLY.sod=sod2;

    printf("mjd:%d sod:%lf\n",mjd2,sod2);
    printf("sta1:%lf sta2:%lf sta3:%lf\n",stax[0],stax[1],stax[2]);
    memset(obj->sta.rleng, 0, sizeof(obj->sta.rleng));
    xyzblh(stax, 1.0, 0, 0, 0, 0, 0, geod);
    //printf("%lf %lf %lf %lf %lf %lf\n", sta->x[0], sta->x[1], sta->x[2], geod[0], geod[1], geod[2]);
    rot_enu2xyz(geod[0], geod[1], rot_l2f);
    /*********** Initial control Variables ******/
    // Keep modeling
    for (isat = 0; isat < DLY.nprn; isat++)
    {
        ddelay = 0.1;
        delay = 0;
        obj->sta.iode[isat] = -2; /* initilize the iode here */
        int itr=0;
        while (fabs(ddelay) > 1e-9)
        {
            timinc(mjd, sod, -delay, &jd_send, &sod_send);
            if (!(lorb = Sat_v_readOrbit(DLY.cprn[isat], jd_send, sod_send, xsat_f, obj->sta.iode[isat])))
            {
                break;
            }
            // geometric distance
            for (j = 0; j < 3; j++)
            {
                r1[j] = xsat_f[j] - stax[j];
            }
            r1leng = sqrt(dot(3, r1, r1));
            // earth rotation correction
            deltaDwe = E_ROTATE / VEL_LIGHT * (xsat_f[1] * (xsat_f[0] - stax[0]) - xsat_f[0] * (xsat_f[1] - stax[1]));
            r1leng += deltaDwe;
            tdelay = r1leng / VEL_LIGHT;
            ddelay = tdelay - delay;
            delay = tdelay;
            if(itr++>10) break;
        }
        if (!lorb)
        {
            obj->sta.rleng[isat] = 0.0;
            continue;
        }else if (itr>10)
        {
            printf("*****WARNING(BaseStation.c): %s position not convergence! ddelay=%14.13lf\n", DLY.cprn[isat], ddelay);
            obj->sta.rleng[isat] = 0.0;
            continue;
        }
        obj->sta.rleng[isat] = r1leng;
        matmpy(r1, (double*)rot_l2f, dump, 1, 3, 3);
        obj->sta.azim[isat] = atan2(dump[0], dump[1]);
        obj->sta.elev[isat] = atan(dump[2] / sqrt(dump[0] * dump[0] + dump[1] * dump[1]));
    }

    // create sat location buff and return it.
    //char *satbuf=calloc(30*MAXSAT,sizeof(char));
    char *tmpbuf=calloc(30,sizeof(char));
    for(isat=0;isat<DLY.nprn;isat++){
        //sta->elev[isat]=1+isat/180.0*pi;
        //sta->azim[isat]=1+isat/180.0*pi*1.5;
        if(strcmp(DLY.cprn[isat],"")==0)
            continue;
        if (fabs(obj->sta.azim[isat])<1e-9 && fabs(obj->sta.elev[isat])<1e-9)
            continue;
        sprintf(tmpbuf,"%s %.2lf %.2lf\n",DLY.cprn[isat],obj->sta.elev[isat]/pi*180.0,obj->sta.azim[isat]/pi*180.0);
        strcat(outBuf,tmpbuf);
    }
    free(tmpbuf);
    printf("outBuf:%s\n",outBuf);
    return strlen(outBuf);
}
void Rnxeph_initial_t(){
    memset(&BRDEPH,0,sizeof(struct Rnxeph));
    for(int i=0; i<MAXSAT; i++){
        if(index_string("GRECBSJI",DLY.cprn[i][0])!=-1){
            if(DLY.cprn[i][0]!='R'){
                strcpy(BRDEPH.gnsseph[BRDEPH.size_gnssEph].cprn, DLY.cprn[i]);
                BRDEPH.size_gnssEph++;
            }else {
                strcpy(BRDEPH.glseph[BRDEPH.size_glsEph].cprn, DLY.cprn[i]);
                BRDEPH.size_glsEph++;
            }
        }
    }
}

// char StreamObs_m_setEphData(nav_t* nav,int psat){
//     int isat,isys,mjd,week,index;
//     char prn[4] = {0};
//     double sow,sod;
//     satno2id(psat, prn);
//     if (!(strlen(prn)) || -1 == (isys = index_string(SYS, prn[0]))
//         || -1 == (isat = pointer_string(DLY.nprn, DLY.cprn, prn))) {
//         return ' ';
//     }
//     if (SYS[isys] != 'R') {
//         struct GPSEPH ephg;
//         memset(&ephg,0,sizeof(struct GPSEPH));
//         ephg.dt=1e6;
//         //Rnxeph_GPSEPH_initial(&ephg);
//         if(SYS[isys] == 'C'){
//             nav->eph[psat - 1].toc.time -= 14; /*change it into bdt*/
//             nav->eph[psat - 1].toe.time -= 14;
//         }
//         sow = time2gpst(nav->eph[psat - 1].toc, &week); /***Time in GPST****/
//         wksow2mjd(week, sow, &mjd, &sod);
//         strcpy(ephg.cprn, prn);
//         ephg.mjd = mjd;                          //Time in GPS
//         ephg.sod = sod;
//         ephg.a0 = nav->eph[psat - 1].f0;
//         ephg.a1 = nav->eph[psat - 1].f1;
//         ephg.a2 = nav->eph[psat - 1].f2;
//         ephg.aode = nav->eph[psat - 1].iode;
//         ephg.crs = nav->eph[psat - 1].crs;
//         ephg.dn = nav->eph[psat - 1].deln;
//         ephg.m0 = nav->eph[psat - 1].M0;
//         ephg.cuc = nav->eph[psat - 1].cuc;
//         ephg.e = nav->eph[psat - 1].e;
//         ephg.cus = nav->eph[psat - 1].cus;
//         ephg.roota = sqrt(nav->eph[psat - 1].A);
//         ephg.cic = nav->eph[psat - 1].cic;
//         ephg.omega0 = nav->eph[psat - 1].OMG0;
//         ephg.cis = nav->eph[psat - 1].cis;
//         ephg.i0 = nav->eph[psat - 1].i0;
//         ephg.crc = nav->eph[psat - 1].crc;
//         ephg.omega = nav->eph[psat - 1].omg;
//         ephg.omegadot = nav->eph[psat - 1].OMGd;
//         ephg.idot = nav->eph[psat - 1].idot;
//         ephg.resvd0 = nav->eph[psat - 1].code;
//         ephg.resvd1 = nav->eph[psat - 1].flag;
//         ephg.accu = nav->eph[psat - 1].sva;
//         ephg.hlth = nav->eph[psat - 1].svh;
//         ephg.aodc = nav->eph[psat - 1].iodc;
//         ephg.tgd = nav->eph[psat - 1].tgd[0];
//         ephg.tgd1 = nav->eph[psat - 1].tgd[1];
//         /*bdtime toe & week*/
//         ephg.toe = time2gpst(nav->eph[psat-1].toe,&week);
//         ephg.week = week;
//         //	memcpy(ephg.tgd,nav->eph[isat-1].tgd,sizeof(double)*4);
//         ephg.aode = genAode(SYS[isys],ephg.mjd,ephg.sod,ephg.toe,ephg.aode,&ephg);

//         // store to BRDEPH
//         index=map_gpseph_find(BRDEPH.gnsseph, ephg.cprn);
//         if(index==-1){
//             printf("*****WARNING(StreamObs.c): %s is not used in session.obj!\n", ephg.cprn);
//         }else{
//             memset(&BRDEPH.gnsseph[index],0,sizeof(struct GPSEPH));
//             BRDEPH.gnsseph[index]=ephg;
//         }
//         // BRDEPH.gnsseph.m_type = SYS[isys];
//     }else{
//         struct GLSEPH ephr;
//         memset(&ephr,0,sizeof(struct GLSEPH));
//         ephr.dt=1e6;
//         //Rnxeph_GLSEPH_initial(&ephr);
//         int week;
//         psat = atoi(prn + 1);
//         strcpy(ephr.cprn,prn);
//         memcpy(ephr.pos,nav->geph[psat-1].pos,sizeof(double) * 3);
//         memcpy(ephr.vel,nav->geph[psat-1].vel,sizeof(double) * 3);
//         memcpy(ephr.acc,nav->geph[psat-1].acc,sizeof(double) * 3);
//         for(int i = 0;i < 3;i++){
//             ephr.pos[i] /= 1e3;
//             ephr.vel[i] /= 1e3;
//             ephr.acc[i] /= 1e3;
//         }
//         ephr.frenum = nav->geph[psat-1].frq;
//         ephr.gamma = nav->geph[psat-1].gamn;
//         ephr.tau = -nav->geph[psat-1].taun;
//         ephr.health = nav->geph[psat-1].svh;
//         ephr.age = nav->geph[psat-1].age;
//         gtime_t tk = gpst2utc(nav->geph[psat-1].tof); /*change it back into utc*/
//         ephr.tk = time2gpst(tk,&week);
//         double sow=time2gpst(nav->geph[psat-1].toe,&week);/*GPST*/
//         wksow2mjd(week,sow,&ephr.mjd,&ephr.sod);
//         ephr.aode = nav->geph[psat - 1].iode;
//         ephr.aode = genAode(SYS[isys], ephr.mjd, ephr.sod, 0.0, ephr.aode, NULL);

//         // store to BRDEPH
//         index=map_glseph_find(BRDEPH.glseph, ephr.cprn);
//         if(index==-1){
//             printf("*****WARNING(StreamObs.c): %s is not used in session.obj!\n", ephr.cprn);
//         }else{
//             memset(&BRDEPH.glseph[index],0,sizeof(struct GLSEPH));
//             BRDEPH.glseph[index]=ephr;
//         }
//     }
//     return SYS[isys];
// }
